package com.orangelife.mobile.complaints.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.common.jump.LocationJumper;
import com.common.sp.CommSp2;
import com.common.sp.UserSp;
import com.common.util.OrangePhoneUtil;
import com.curry.android.net.NetworkUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.StringUtil;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.adapter.MyImageViewGridAdapter;
import com.orangelife.mobile.common.biz.Photo;
import com.thirdsdk.qiniu.QiniuService;
import com.orangelife.mobile.complaints.biz.Complaints;
import com.orangelife.mobile.photo.ImageActivity;
import com.orangelife.mobile.photo.MyGridView;
import com.orangelife.mobile.photo.PhotoActivity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 添加投诉建议
 * <p/>
 * Created by YangWei
 * on 2015/11/11.
 */
public class ComplainAdviceAddActivity extends OrangeLifeBaseActivity {

    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.iv_title_right)
    ImageView ivTitleRight;
    @Bind(R.id.etSugContent)
    EditText etSugContent;
    @Bind(R.id.myGridview)
    MyGridView myGridview;

    @Bind(R.id.tv_city)
    TextView tv_City;

    @Bind(R.id.rlSelectCity)
    RelativeLayout rlSelectCity;
    @Bind(R.id.rlSelectNeighbourhood)
    RelativeLayout rlSelectNeighbourhood;
    @Bind(R.id.rlSelectDepartment)
    RelativeLayout rlSelectDepartment;
    @Bind(R.id.rlSelectRoomNumber)
    RelativeLayout rlSelectRoomNumber;

    @Bind(R.id.tv_neighbourhood)
    TextView tv_Neighbourhood;


    @Bind(R.id.tv_department)
    TextView tvDepartment;
    @Bind(R.id.tv_room_number)
    TextView tvRoomNumber;
    @Bind(R.id.btnComSug)
    Button btnComSug;
    /**
     * 照片路径
     */
    private List<String> paths;
    /**
     * gridview的adapter
     */
    private MyImageViewGridAdapter gvAdapter;

    private Map<String, Object> map;

    private Complaints complaints = Complaints.getInstance();

    private String commID = "", buildingID = "", apartmentID = "";
    private String phone = "";
    private String commName = "";
    private String city = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_complain_advice_add);
        ButterKnife.bind(this);
        initCommInfo();
        initView();
        setGridView();
        setListener();
    }

    private void initCommInfo() {
        phone = CommSp2.getCommPmPhone();
    }

    /**
     * 初始化界面
     */
    private void initView() {
        tvTitle.setText("投诉建议");
        city = CommSp2.getCityName();
        tv_City.setText(city);
        commName = CommSp2.getCommName();
        commID = CommSp2.getCommID();
        tv_Neighbourhood.setText(commName);
        ivTitleRight.setVisibility(View.VISIBLE);
        ivTitleRight.setBackgroundResource(R.drawable.icon_phone);
    }

    /**
     * 赋值并判断
     */
    private void setListener() {
        btnComSug.setOnClickListener(listener);
        rlSelectCity.setOnClickListener(listener);
        rlSelectNeighbourhood.setOnClickListener(listener);
        rlSelectDepartment.setOnClickListener(listener);
        rlSelectRoomNumber.setOnClickListener(listener);
        ivTitleRight.setOnClickListener(listener);
    }


    /**
     * 给照片的gridview设置adapter和监听器
     */
    private void setGridView() {
        paths = new ArrayList<>();
        gvAdapter = new MyImageViewGridAdapter(
                ComplainAdviceAddActivity.this, paths, 4);
        myGridview.setAdapter(gvAdapter);
        gvAdapter.notifyDataSetChanged();

        myGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view,
                                    int position, long arg3) {
                if (position == paths.size()) {
                    Intent intent = new Intent(
                            ComplainAdviceAddActivity.this,
                            PhotoActivity.class);
                    startActivityForResult(intent, 5);
                } else {
                    Intent intent = new Intent(
                            ComplainAdviceAddActivity.this,
                            ImageActivity.class);
                    intent.putExtra("position", position);
                    intent.putExtra("path", paths.get(position));
                    startActivityForResult(intent, 88);
                }
            }
        });
    }

    /** 拨打客服电话，第一次选择外部选择小区的电话；后面，在选择小区之后，更换URL返回的电话号码； */
    public void dial() {
        if (StringUtil.isContainBlank(phone)) {
            OrangePhoneUtil.callCustomerService2(ComplainAdviceAddActivity.this);
        } else {
            OrangePhoneUtil.callCommProperty(ComplainAdviceAddActivity.this, phone, commName);
        }
    }

    /**
     * 定义监听器
     */
    Photo photo = null;
    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            photo = new Photo(ComplainAdviceAddActivity.this);
            switch (v.getId()) {
                case R.id.iv_title_right:
                    dial();
                    break;
                case R.id.rlSelectCity:
                    jumpSelectHouse(CITY, "");
                    break;
                case R.id.rlSelectNeighbourhood:
                    if (!StringUtil.isBlank(city)) {
                        jumpSelectHouse(COMM, city);
                    } else ToastHelper.getInstance()._toast("请先选择城市");
                    break;
                case R.id.rlSelectDepartment:
                    if (!StringUtil.isBlank(commID)) {
                        jumpSelectHouse(BUILDING, commID);
                    } else ToastHelper.getInstance()._toast("请先选择小区");
                    break;
                case R.id.rlSelectRoomNumber:
                    if (!StringUtil.isBlank(buildingID)) {
                        jumpSelectHouse(APARTMENT, buildingID);
                    } else {
                        ToastHelper.getInstance()._toast("请先选择栋座（单元）");
                    }
                    break;
                case R.id.btnComSug:
                    if (!NetworkUtil
                            .isConnectedNet(ComplainAdviceAddActivity.this)) {
                        Toast.makeText(
                                ComplainAdviceAddActivity.this,
                                getResources().getString(R.string.net_disconnected),
                                Toast.LENGTH_SHORT).show();
                    } else if (StringUtil.isContainBlank(etSugContent.getText()
                            .toString())) {
                        ToastHelper.getInstance()._toast(
                                getResources().getString(
                                        R.string.complaints_suggestions_judgment));
                    } else if (StringUtil.isContainBlank(tvDepartment.getText()
                            .toString())) {
                        ToastHelper.getInstance()._toast(
                                getResources().getString(
                                        R.string.complaints_select_department));
                    } else if (StringUtil.isContainBlank(tvRoomNumber.getText()
                            .toString())) {
                        ToastHelper.getInstance()._toast(
                                getResources().getString(
                                        R.string.complaints_select_room_number));
                    } else {
                        map = new HashMap<>();
                        String trueName = UserSp.getNickname();
                        map.put("commID", commID);
                        map.put("apartmentID", apartmentID);
                        map.put("content", etSugContent.getText().toString());
                        map.put("userName", trueName);
                        map.put("userPhone", UserSp.getRegPhone());
                        map.put("remark", "");

                        showDialog(ComplainAdviceAddActivity.this);
                        if ("[]".equals(paths.toString())) {
                            String fileNames = null;
                            complaints.addComplainSuggestion(map, fileNames, new AddComplainHandler(ComplainAdviceAddActivity.this));
                        } else {
                            QiniuService qiniu = new QiniuService();
                            qiniu.imgUpload(paths, new QiniuService.QiniuListener() {

                                @Override
                                public void request(String fileNames) {
                                    if (fileNames.equals("500")) {
                                        ToastHelper
                                                .getInstance()
                                                ._toast(getResources()
                                                        .getString(
                                                                R.string.complaintes_save_fail));
                                        return;
                                    }
                                    complaints.addComplainSuggestion(map, fileNames, new AddComplainHandler(ComplainAdviceAddActivity.this));
                                }
                            });
                        }
                    }
                    break;
                case R.id.btn_take_photo:
                    photo.takePhoto();
                    break;
                case R.id.btn_pick_photo:
                    photo.openAlbum();
                    break;
                default:
                    break;
            }
        }

    };


    public static final int SELECT_TYPE = 0;
    private static final int CITY = 1;
    private static final int COMM = 2;
    private static final int BUILDING = 3;
    private static final int APARTMENT = 4;

    private void jumpSelectHouse(int type, String id) {
        LocationJumper.jumpSelectHouse(type, id, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 5 && resultCode == 99) {
            if (data != null) {
                String photoPath = data.getStringExtra("photoPath");
                addPhotoPath(photoPath);
            } else {
                if (photo.photoUri != null) {
                    String photoPath = photo.photoUri.getPath();
                    addPhotoPath(photoPath);
                }

            }
        } else if (requestCode == 6 && resultCode == 99) {
            if (data != null) {
                String photoPath = Photo.getPath(data);
                addPhotoPath(photoPath);
            }

        } else if (requestCode == 88 && resultCode == 88) {
            if (data != null) {
                Bundle bundle = data.getExtras();
                int position = bundle.getInt("position");
                paths.remove(position);
                notifyGridView();
            }
        }
        gvAdapter.notifyDataSetChanged();
        if (requestCode == SELECT_TYPE && resultCode == RESULT_OK) {
            if (data != null) {
                Map<String, Object> map = (Map<String, Object>) data.getExtras().getSerializable("zoning");
                int type = data.getIntExtra("selectType", 0);
                setData(type, map);
            }
        }
    }

    /**
     * 处理选择房号返回的数据
     *
     * @param type 类型，1 城市，2 小区，3 楼栋 ，4 房号
     * @param map  数据
     */
    private void setData(int type, Map<String, Object> map) {
        String city = String.valueOf(map.get("city"));
        String comm = String.valueOf(map.get("comm"));
        String commID = String.valueOf(map.get("commID"));
        String buildID = String.valueOf(map.get("buildID"));
        String building = String.valueOf(map.get("building"));
        String apartment = String.valueOf(map.get("apartment"));
        String apartmentID = String.valueOf(map.get("apartmentID"));
        String tmpPhone = String.valueOf(map.get("phone"));
        for (int i = 1; i <= type; i++) {
            switch (i) {
                case CITY:
                    if (!StringUtil.isBlank(city)) {
                        tv_City.setText(city);
                        this.city = city;
                    }
                    break;
                case COMM:
                    if (!StringUtil.isBlank(comm)) {
                        commName = comm;
                        phone = tmpPhone;
                        tv_Neighbourhood.setText(comm);
                        this.commID = commID;
                    }
                    break;
                case BUILDING:
                    if (!StringUtil.isBlank(building)) {
                        tvDepartment.setText(building);
                        this.buildingID = buildID;
                    }
                    break;
                case APARTMENT:
                    if (!StringUtil.isBlank(apartment)) {
                        tvRoomNumber.setText(apartment);
                        this.apartmentID = apartmentID;
                    }
                    break;
            }
        }
    }

    /**
     * 添加路径到列表
     */
    private void addPhotoPath(String photoPath) {
        paths.add(photoPath);
        notifyGridView();
    }

    /**
     * 更新GridView页面
     */
    private void notifyGridView() {
        gvAdapter.resetImage(paths);
        gvAdapter.notifyDataSetChanged();
    }

    static class AddComplainHandler extends Handler {
        private WeakReference<ComplainAdviceAddActivity> complainAdviceAddActivity = null;

        public AddComplainHandler(ComplainAdviceAddActivity activity) {
            complainAdviceAddActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            ComplainAdviceAddActivity act = complainAdviceAddActivity.get();

            if (act != null) {
                switch (msg.what) {
                    case 1:
                        String errInfo = JSONHelper.jsonToMap(msg.obj.toString())
                                .get("errInfo").toString();
                        if (errInfo.equals("OK")) {
                            DialogHelper.closeDialog(act.dialog);
                            ToastHelper.getInstance()._toast(act.getResources().getString(R.string.submit_success));
                            IntentHelper.getInstances().getIntent(act, ComplainAddSuccessActivity.class);
                            act.finish();
                        } else {
                            DialogHelper.closeDialog(act.dialog);
                            ToastHelper.getInstance()._toast(
                                    act.getResources().getString(
                                            R.string.complaintes_sumbite_fail));
                        }
                        break;
                    case 500:
                        ToastHelper.getInstance()._toast(
                                msg.obj.toString());
                        break;
                    case 1011:
                        act.isLogin(act.dialog);
                        break;

                    default:
                        break;
                }
                if (act.dialog != null) {
                    DialogHelper.closeDialog(act.dialog);
                }
            }
        }
    }
}
